<?php
/*
    where :    
    update :
    insert : 
 */
class BaseModel {
	public    $db;
    protected $table_pre = true;                // 是否添加表前缀
	protected $options=array();
    protected $methods = array('fields', 'where', 'order', 'limit', 'group');
	
    public    $tableName = '';
    public    $errors = array();

	function __construct() {
		$this->db = new MysqlNew(
			$GLOBALS["public_appconfig"]["mysql"]["host"].':'.$GLOBALS["public_appconfig"]["mysql"]["port"],
			$GLOBALS["public_appconfig"]["mysql"]["user"],
			$GLOBALS["public_appconfig"]["mysql"]["pass"],
			$GLOBALS["public_appconfig"]["mysql"]["db"],
			$GLOBALS["public_appconfig"]["mysql"]["charset"]
		);

        $this->_tableName();
	}

    protected function _tableName() {
        $tableName = $this->tableName();

        empty($tableName) && die('lack table function');

        $this->tableName = $this->table_pre ? $GLOBALS["public_appconfig"]["mysql"]["table_pre"].$tableName : $tableName;
    }

    public function getTable() {
        return $this->tableName;
    }
	/*
 	 * 查询方法
   	 */
	function select() {
        
        $this->fetch_option();

        $where = $this->options['where'].$this->options['group'].$this->options['order'].$this->options['limit'];

        if($this->db->select($this->tableName, $this->options['fields'], $where)) {
            return $this->_fetch();
        } else {
            return array();
        }
	}

	/*
 	 * 查询方法
   	 */
	function selectAll() {
        $this->fetch_option();

        $where = $this->options['where'].$this->options['group'].$this->options['order'];

        if($this->db->select($this->tableName, $this->options['fields'], $where)) {
            return $this->_fetch();
        } else {
            return array();
        }
	}

	/*
 	 * 查询方法
   	 */
	function getOne() {
        $this->fetch_option();

        $where = $this->options['where'].$this->options['order'].' LIMIT 1';

        if($this->db->select($this->tableName, $this->options['fields'], $where)) {
            return $this->_fetch()[0];
        } else {
            return array();
        }
	}

    /*
     * 查询总数
     * pk ：表主键
     */
    function count($pk = null) {
        $this->fetch_option();

        $count = 'count(*)';
        if(!is_null($pk)) {
            $count = 'count('.$pk.')';
        }

        $count .= ' as total';

        $where = $this->options['where'];

        if($this->db->select($this->tableName, $count, $where)) {
            return (int)$this->_fetch()[0]['total'];
        } else {
            return array();
        }
    }


	/*
 	 * 查询方法
   	 */
	function insert($data=array()) {
        if(empty($data)) {
            return false;
        }

        //过滤入库信息
        $fields = '`'.implode('`,`', array_keys($data)).'`';
        $data = array_map('addslashes', $data);
        $values = "'".implode("','", $data)."'";

        if($this->db->insert($this->tableName, $fields, $values)) {
            return $this->db->insert_id();
        }

        return false;
	}

	/*
 	 * 查询方法
   	 */
	function update($data) {
        if(empty($data)) {
            return false;
        }

        $this->fetch_option();

        array_walk($info,"htmlspecialchars");
        foreach ($data as $key => $value) {
            $set .= $key."='".$value."',";
        }

        $sets = trim($set, ',');

        if($this->db->update($this->tableName, $sets, $this->options['where'])) {
            return $this->db->db_affected_rows();
        } else {
            return false;
        }
	}

	/*
 	 * 查询方法
   	 */
	function delete() {

        $this->fetch_option();

        if($this->db->delete($this->tableName, $this->options['where'])) {
            return $this->db->db_affected_rows();
        } else {
            return false;
        }
	}

    function query($sql) {
        if($this->db->query($sql)) {
            $fetch = $this->_fetch();
            return  $fetch ? $fetch : $this->db->db_affected_rows();
        } else {
            return false;
        }
    }
    /*
     * 自定义执行错误信息
     */
    function setError($message='') {
        $this->errors[] = $message;
    }

    /*
     * 获取定义的错误
     */
    function getError() {
        return $this->errors;
    }

    protected function _fetch() {
        $res = array();
        while ($row = $this->db->fetch_assoc()) {
            $res[] = $row;
        }

        $this->clear();
        return $res;
    }

	/**
     * 利用__call方法实现一些特殊的Model方法
     * @access public
     * @param string $method 方法名称
     * @param array $args 调用参数
     * @return mixed
     */
    public function __call($method,$args) {
        if(in_array(strtolower($method), $this->methods, true)) {
            $this->options[strtolower($method)] = $args[0];

            return $this;
        } else {
            die($method.'-扩展方法不存在');
        }
    }

    protected function fetch_option() {
        foreach ($this->methods as $key => $value) {
            call_user_func(array($this, '_'.$value));
        }
    }

    protected function _fields() {
        $fields = '*';

        if(is_string($this->options['fields'])) {
            $fields = $this->options['fields'];
        } else if (is_array($this->options['fields'])) {
			$fields = '`'.implode('`, `', $this->options['fields']).'`';
        }

        $this->options['fields'] = $fields;
    }

    protected function _where() {

        $where = ' 1=1';
        if(empty($this->options['where'])) {
            $where = ' 1=1';
        } else if(is_string($this->options['where'])) {
            $where = $this->options['where'];
        } else if (is_array($this->options['where'])) {
			foreach ($this->options['where'] as $key => $value) {
				$where .= ' AND '.$key." = '".$value."'";
			}
        }

        $this->options['where'] = $where;
    }

    protected function _order() {
        $this->options['order'] = (isset($this->options['order']) && !empty($this->options['order'])) ? ' ORDER BY '.$this->options['order'] : '';
    }

    protected function _group() {
        $this->options['group'] = (isset($this->options['group']) && !empty($this->options['group'])) ? ' GROUP BY '.$this->options['group'] : '';
    }

    protected function _limit() {
        $this->options['limit'] = (isset($this->options['limit']) && !empty($this->options['limit'])) ? ' LIMIT '.$this->options['limit'] : '';
    }

    protected function clear() {
        $this->options = $this->errors = array();
    }

}